package com.cysion.study.ui.personal

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.cysion.other.color
import com.cysion.other.startActivity_ex
import com.cysion.study.R
import com.cysion.study.entity.AppInfoEntity
import com.cysion.study.helper.UserCache
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.ACache
import com.cysion.study.ktbox.utils.whiteTextTheme
import com.cysion.study.net.ApiClient
import com.cysion.study.ui.NoticeActivity
import com.cysion.study.ui.login.LoginActivity
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.uibox.dialog.CONFIRM
import com.cysion.study.widget.PackageUtils
import com.cysion.study.widget.ShowToast
import com.cysion.study.widget.UIHelper
import com.cysion.study.widget.VersionUtil.getAppVersionCode
import com.cysion.study.widget.VersionUtil.getAppVersionName
import com.cysion.targetfun._subscribe
import kotlinx.android.synthetic.main.activity_setting.*

/**
 * Created by chu on 2019-07-01.
 */
class SettingActivity : BaseActivity(), View.OnClickListener {


    override fun getLayoutId(): Int = R.layout.activity_setting

    override fun initView() {
        whiteTextTheme(color(R.color.main_cl))
        topbar.apply {
            setTitle("设置")
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }
        tv_set_pay.setOnClickListener(this)
        tv_modify_pwd.setOnClickListener(this)
        tv_black.setOnClickListener(this)
        tv_reback.setOnClickListener(this)
        tv_about.setOnClickListener(this)
        tv_clean.setOnClickListener(this)
        tv_update.setOnClickListener(this)
        tv_out.setOnClickListener(this)

        tv_version.setText(PackageUtils.getVersionName(this))

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 ) {
            println("####登录返回"+requestCode)
            setResult(100)
            finish()
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_out -> {
                Alert.normal(self, "提示", "确认退出吗？") { type, msg ->
                    if (type == CONFIRM) {
                        UserCache.clear()
                        UIHelper.jumpForResult(self,LoginActivity::class.java,100)
                        ACache.get(Box.context).put("resetlogin", "1")//为1 说明 更换账号登录后 首页切到首页
                    }
                }

            }
            R.id.tv_set_pay -> {//密码管理
                self.startActivity_ex<SettingPwdActivity>()
            }
            R.id.tv_modify_pwd -> {//
//                self.startActivity_ex<NoticeSettingActivity>()//通知管理
                self.startActivity_ex<NoticeActivity>()//通知列表
            }
            R.id.tv_black -> {//黑名单
                self.startActivity_ex<BlackListActivity>()
            }
            R.id.tv_reback -> {//举报投诉
                self.startActivity_ex<FeedBackActivity>()
            }
            R.id.tv_about -> {//关于
                self.startActivity_ex<AboutActivity>()
            }
            R.id.tv_clean -> {//清除
                ShowToast("清除缓存中...")
                ShowToast("清除成功")
            }
            R.id.tv_update -> {
                getAppUpdate()
//
//                ShowToast("当前已是最新版本")
            }
        }

    }

    private fun getAppUpdate() {
        Alert.loading(this)
        //1,//类型 1、家长端安卓；2、家长端苹果；3、教师端安卓；4、教师端苹果
        ApiClient.api.getAppUpdate("3", UserCache.token).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    try {
                        if (it.version.toInt() != getAppVersionCode().toInt()) {
                            //                        AppContext.showToast("发现新版本");
//                            ifMust = appInfo.data?.ifMust.toString()
                            updateApp(it)
                        } else {
                            tv_version.text = getAppVersionName()
                            ShowToast( "已是最新版本")
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
                _onError {
                    Alert.close()

                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }

    private fun updateApp(obj: AppInfoEntity) {
        //":0,//是否强制下载：1、是；0、否
        var ifMust = false
        if (obj.ifMust == "0") {
            ifMust = true
        } else {
            ifMust = false
        }
        val view = Alert.setup(this, R.layout.dialog_app_update, 0.8f, ifMust, null)
        var iv_close = view.findViewById<ImageView>(R.id.iv_close)
        var tv_content = view.findViewById<TextView>(R.id.tv_content)
        tv_content.text = obj.doc
        var tv_cancel = view.findViewById<TextView>(R.id.tv_cancel)

        if (obj.ifMust == "0") {
            iv_close.visibility = View.VISIBLE
            tv_cancel.visibility = View.VISIBLE
        } else {
            iv_close.visibility = View.GONE
            tv_cancel.visibility = View.GONE
        }
        iv_close.setOnClickListener {
            if (obj.ifMust == "1") {
                ShowToast("您必须更新版本才能使用哦")
                return@setOnClickListener
            } else {
                Alert.close()
            }
        }
        tv_cancel.setOnClickListener {
            if (obj.ifMust == "1") {
                ShowToast("您必须更新版本才能使用哦")
                return@setOnClickListener
            } else {
                Alert.close()
            }
        }


        view.findViewById<TextView>(R.id.tv_confirm).setOnClickListener {
            if (TextUtils.isEmpty(obj.link)) {
                ShowToast("更新链接地址错误")
                return@setOnClickListener
            }
//                val uri = Uri.parse("http://www.google.com")
            val uri = Uri.parse(obj.link)
            val it = Intent(Intent.ACTION_VIEW, uri)
            self.startActivity(it)
            Alert.close()
        }
    }

    override fun closeMvp() {
    }
}